package cn.lixin.hrm;

import cn.lixin.hrm.domain.LoginUser;
import cn.lixin.hrm.domain.Permission;
import cn.lixin.hrm.mapper.LoginUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private LoginUserMapper loginUserMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LoginUser loginUser = loginUserMapper.loadUserByUsername(username);
        if (loginUser == null)
            throw new RuntimeException("用户名不存在");

        ArrayList<GrantedAuthority> permissons = new ArrayList<>();
        // 查询用户的所有权限
        List<Permission> userPermissions = loginUserMapper.getUserPermissions(loginUser.getId());
        // 将权限遍历添加到SpringSecurity封装的User的权限list中
        userPermissions.stream().forEach(userPermission->{
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(userPermission.getSn());
            permissons.add(simpleGrantedAuthority);
        });
        User user = new User(loginUser.getUsername(), loginUser.getPassword(), permissons);
        return user;
    }
}
